package com.example.eeuse.controller;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.eeuse.mapper.DocumentMapper;
import com.example.eeuse.model.Document;
import lombok.RequiredArgsConstructor;
import org.dromara.easyes.annotation.IndexName;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN;
import static cn.hutool.core.date.DatePattern.UTC_MS_WITH_ZONE_OFFSET_PATTERN;

/**
 * 测试使用Easy-ES
 * <p>
 * Copyright © 2021 xpc1024 All Rights Reserved
 **/
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestUseEeController {
    private final DocumentMapper documentMapper;

    @GetMapping("/createIndex")
    public Boolean createIndex() {
        // 1.初始化-> 创建索引(相当于mysql中的表)
        return documentMapper.createIndex();
    }

    @GetMapping("/insert")
    public Integer insert() {
        // 2.初始化-> 新增数据
        Document document = new Document();
        document.setTitle("老汉");
        document.setContent("推*技术过硬");
        document.setType(3);
        document.setGmtCreate(DateUtil.format(new Date(),UTC_MS_WITH_ZONE_OFFSET_PATTERN));
        String indexName = Document.class.getAnnotation(IndexName.class).value()+"_"+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return documentMapper.insert(document,indexName);
    }

    @GetMapping("/search")
    public List<Document> search() {
        // 3.查询出所有标题为老汉的文档列表
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(Document::getTitle, "老汉");
        List<Document> documentList = documentMapper.selectList(wrapper);
        System.out.println("dsl query result:"+documentList.size());
        return documentList;
    }

    @GetMapping("/searchsql")
    public String searchsql() {
        DateTime dt = DateUtil.parse("2023-09-16 00:00:00", DatePattern.NORM_DATETIME_PATTERN);
        String queryDate = DateUtil.format(dt, UTC_MS_WITH_ZONE_OFFSET_PATTERN);
        String jsonResult = documentMapper.executeSQL("select * from document where content like '%技术过硬%' and gmtCreate>= '"+queryDate+"'");
        return jsonResult;
    }
}
